package cn.xiyue.production.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import cn.xiyue.production.R;
import cn.xiyue.production.base.CallableActivity;

public class BuyActivity extends CallableActivity implements View.OnClickListener {

    private TextView tv_gold;
    private EditText et_location;
    private EditText et_id;
    private Button btn_buy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy);
        initView();
    }

    private void initView() {
        tv_gold = (TextView) findViewById(R.id.tv_gold);
        et_location = (EditText) findViewById(R.id.et_location);
        et_id = (EditText) findViewById(R.id.et_id);
        btn_buy = (Button) findViewById(R.id.btn_buy);
        btn_buy.setOnClickListener(this);

        refresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_buy:
                submit();
                break;
        }
    }

    private void submit() {
        // validate
        String location = et_location.getText().toString().trim();
        if (TextUtils.isEmpty(location)) {
            showToast("位置不能为空");
            return;
        }

        String id = et_id.getText().toString().trim();
        if (TextUtils.isEmpty(id)) {
            showToast("供应原料ID不能为空");
            return;
        }

        // TODO validate success, do something
        async(requestApi.buyMaterial(location,id,1),value -> {
            showToast("购买成功！");
            refresh();
        });
    }

    private void refresh(){
        async(requestApi.getFactoryInfo(1),value -> {
            int gold = value.getData().get(0).getGold();
            tv_gold.setText(String.format("工厂资金：%d",gold));
        });
    }
}